var fs = require('fs');
var mqtt = require('mqtt');
var debug = require('debug')('routes:tvad');
var _ = require('underscore');

var Sim = require('../models/sim');
var Box = require('../models/boxes');
var client = mqtt.connect('mqtt://115.28.90.45:1883');//192.168.199.165:1885

module.exports = function (app) {

    /*
     * 图片列表
     */
    app.get('/tvad/list', function (req, res, next) {

        //获取用户ID
        var userid = req.session.user._id;
        //按权限封装查询参数
        var params;
        if (req.session.permissionMap[1021]) {
            params = {}
        } else {
            params = {'owner': userid}
        }

        //查询箱子
        Box.find(params).exec().then(function (boxes) {
            var boxids = _.flatten(_.pluck(boxes, 'box_id'));
            return Sim.find().where('box_id').in(boxids).exec();
        }).then(function (sims) {
            debug('sims are %o', sims);
            res.render('tvad/tvad_index', {sims: sims});
        }).error(function (err) {
            res.send({success: false, err: err});
        });

    });

    /**
     * 文件上传重命名
     */
    app.post('/tvad/uploadVideoPic', function (req, res) {
        try {

            var userid = req.session.user._id;
            var targetPath = './public/uploads/tvad/' + userid + '/';

            if (!fs.existsSync(targetPath)) {
                fs.mkdirSync(targetPath);
            }

            //重命名为上传前名称
            fs.renameSync('./public/uploads/' + req.files.Filedata.name, targetPath + req.files.Filedata.originalname);
            console.log(req.files.Filedata.name + "`````" + req.files.Filedata.originalname);
        } catch (e) {
            console.log(e);
        }

        res.send(true);
    });

    app.get('/tvad/filesSync', function (req, res) {
        var topic = req.query.topic;
        var userid = req.session.user._id;
        var targetPath = './public/uploads/tvad/' + userid + '/';
        var urlPath = 'uploads/tvad/' + userid + '/';

        fs.readdir(targetPath, function (err, orignfiles) {
            //err 为错误 , files 文件名列表包含文件夹与文件
            if (err) {
                console.log('error:\n' + err);
                return;
            }

            var files = [];
            for (var i = orignfiles.length - 1; i >= 0; i--) {
                files[i] = urlPath + orignfiles[i];
            }
            ;

            //client.subscribe('presence');
            //client.publish(topic+'dltopic', files.toString());
            client.publish(topic, JSON.stringify({"type": "dltopic", "message": files.toString()}));
            client.on('message', function (topic, message) {
                // message is Buffer
                console.log(message.toString());
            });

            //client.end();//关闭连接

            res.setHeader('Content-Type', 'text/html');
            res.send(true);

        });


    });


    app.get('/tvad/filesList', function (req, res) {
        var userid = req.session.user._id;
        var targetPath = './public/uploads/tvad/' + userid + '/';
        var urlPath = '/uploads/tvad/' + userid + '/';
        if (fs.existsSync(targetPath)) {
            var orignfiles = fs.readdirSync(targetPath);
        } else {
            var orignfiles = [];
        }
        var files = [];
        for (var i = orignfiles.length - 1; i >= 0; i--) {
            files[i] = {
                url: urlPath + orignfiles[i],
                name: orignfiles[i]
            };
        }
        ;
        res.send(files);
    });

    /**
     * 删除文件
     */
    app.get('/tvad/delfile', function (req, res) {
        var topic = req.query.topic;
        var name = req.query.filename;
        var userid = req.session.user._id;
        var targetPath = './public/uploads/tvad/' + userid + '/';
        console.log(name + '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
        var files = fs.unlink(targetPath + name, function (err) {
            if (err) {
                res.send(false);
            } else {
                res.send(true);
            }
        });

    });

    /**
     * 替换设备单个文件
     */
    app.get('/tvad/replace', function (req, res) {
        var name = req.query.filename;
        var topic = req.query.topic;
        var userid = req.session.user._id;
        var urlPath = 'uploads/tvad/' + userid + '/';
        //client.publish(topic+'replaceTopic', name);
        client.publish(topic, JSON.stringify({"type": "replaceTopic", "message": urlPath + name}));

        res.send(true);
    });

    app.get('/tvad/openSurprised', function (req, res) {
        var phone = req.query.phone;
        var msg = "open" + req.query.index;
        client.publish(phone, msg);
        client.publish('openSurprised', '');
        res.setHeader('Content-Type', 'text/html');
        res.send(true);
    });

}
